﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace Kaleidoscope
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           

        }

        protected override void OnError(EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            Exception exception = context.Server.GetLastError();

            string errorInfo =
     "<br>Offending URL: " + context.Request.Url.ToString() +
     "<br>Source: " + exception.Source +
     "<br>Message: " + exception.Message +
     "<br>Stack trace: " + exception.StackTrace;

            context.Response.Write(errorInfo);

            //this.messageLabel.Text = exception.Message;
            //this.messageLabel.Visible = true;
            context.Server.ClearError();
            base.OnError(e);
        }

        private const int maximalLength = 1024*1024;

        protected void buttonUpload_Click(object sender, EventArgs e)
        {

            if (fileUploader.HasFile)
            {
                int fileLength = fileUploader.PostedFile.ContentLength;
                if (fileLength > maximalLength)
                {
                    messageLabel.Text = "File length " + fileLength + " exceeds maximal value " + maximalLength;
                    messageLabel.Visible = true;
                }
                else
                {
                    messageLabel.Visible = false;
                    byte[] buffer = new byte[fileUploader.PostedFile.ContentLength];
                    int bytesRead =0;
                    do
                    {
                        int count = fileUploader.PostedFile.InputStream.Read(buffer, bytesRead, fileLength);
                        bytesRead+=count;
                    } 
                    while (bytesRead<fileLength);
                    messageLabel.Text = bytesRead + " bytes read";
                    messageLabel.Visible = true;
                }
            }
            else
            {
                this.messageLabel.Text = "No file to upload. Enter file name";
                this.messageLabel.Visible = true;
            }
        }
    }
}
